<template>
  <el-dialog
    v-model="dialogVisible"
    :title="mode === 'create' ? '新建预约' : '编辑预约'"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="appointment-form"
    >
      <el-row :gutter="20">
        <!-- 患者信息 -->
        <el-col :span="24">
          <el-card class="form-section">
            <template #header>
              <span>患者信息</span>
            </template>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="选择患者" prop="patientId" required>
                  <el-select
                    v-model="form.patientId"
                    placeholder="请选择患者"
                    filterable
                    remote
                    :remote-method="searchPatients"
                    :loading="patientLoading"
                    style="width: 100%"
                    @change="handlePatientChange"
                  >
                    <el-option
                      v-for="patient in patients"
                      :key="patient.id"
                      :label="`${patient.name} - ${patient.phone}`"
                      :value="patient.id"
                    >
                      <div class="patient-option">
                        <span class="patient-name">{{ patient.name }}</span>
                        <span class="patient-info">{{ patient.phone }} | {{ patient.gender === 'male' ? '男' : '女' }} | {{ patient.age }}岁</span>
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              
              <el-col :span="12">
                <el-form-item>
                  <el-button type="success" @click="handleCreatePatient">
                    <el-icon><Plus /></el-icon>
                    新建患者
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
            
            <!-- 选中患者的详细信息 -->
            <div v-if="selectedPatient" class="selected-patient">
              <el-divider content-position="left">患者详情</el-divider>
              <div class="patient-details">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <div class="detail-item">
                      <label>姓名：</label>
                      <span>{{ selectedPatient.name }}</span>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="detail-item">
                      <label>性别：</label>
                      <span>{{ selectedPatient.gender === 'male' ? '男' : '女' }}</span>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="detail-item">
                      <label>年龄：</label>
                      <span>{{ selectedPatient.age }}岁</span>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="detail-item">
                      <label>手机号：</label>
                      <span>{{ selectedPatient.phone }}</span>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="detail-item">
                      <label>身份证：</label>
                      <span>{{ selectedPatient.idCard || '-' }}</span>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="detail-item">
                      <label>血型：</label>
                      <span>{{ selectedPatient.bloodType || '-' }}</span>
                    </div>
                  </el-col>
                </el-row>
                
                <div v-if="selectedPatient.allergies" class="detail-item full-width">
                  <label>过敏史：</label>
                  <span class="allergy-info">{{ selectedPatient.allergies }}</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <!-- 预约信息 -->
        <el-col :span="24">
          <el-card class="form-section">
            <template #header>
              <span>预约信息</span>
            </template>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="体检套餐" prop="packageId" required>
                  <el-select
                    v-model="form.packageId"
                    placeholder="请选择体检套餐"
                    style="width: 100%"
                    @change="handlePackageChange"
                  >
                    <el-option
                      v-for="pkg in packages"
                      :key="pkg.id"
                      :label="pkg.name"
                      :value="pkg.id"
                    >
                      <div class="package-option">
                        <div class="package-name">{{ pkg.name }}</div>
                        <div class="package-price">¥{{ pkg.price }}</div>
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              
              <el-col :span="12">
                <el-form-item label="预约日期" prop="appointmentDate" required>
                  <el-date-picker
                    v-model="form.appointmentDate"
                    type="date"
                    placeholder="请选择预约日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    :disabled-date="disabledDate"
                    style="width: 100%"
                    @change="handleDateChange"
                  />
                </el-form-item>
              </el-col>
              
              <el-col :span="12">
                <el-form-item label="预约时间" prop="appointmentTime" required>
                  <el-select
                    v-model="form.appointmentTime"
                    placeholder="请选择预约时间"
                    style="width: 100%"
                    :disabled="!form.appointmentDate"
                  >
                    <el-option
                      v-for="time in availableTimes"
                      :key="time.value"
                      :label="time.label"
                      :value="time.value"
                      :disabled="time.disabled"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              
              <el-col :span="12">
                <el-form-item label="负责医生" prop="doctor">
                  <el-select
                    v-model="form.doctor"
                    placeholder="请选择负责医生"
                    style="width: 100%"
                    clearable
                  >
                    <el-option
                      v-for="doctor in doctors"
                      :key="doctor.id"
                      :label="doctor.name"
                      :value="doctor.name"
                    >
                      <div class="doctor-option">
                        <span class="doctor-name">{{ doctor.name }}</span>
                        <span class="doctor-title">{{ doctor.title }}</span>
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <!-- 选中套餐的详细信息 -->
            <div v-if="selectedPackage" class="selected-package">
              <el-divider content-position="left">套餐详情</el-divider>
              <div class="package-details">
                <div class="package-info">
                  <div class="package-header">
                    <h4>{{ selectedPackage.name }}</h4>
                    <el-tag type="success" size="large">¥{{ selectedPackage.price }}</el-tag>
                  </div>
                  <p class="package-description">{{ selectedPackage.description }}</p>
                  
                  <div class="package-items">
                    <h5>包含项目：</h5>
                    <div class="items-grid">
                      <el-tag
                        v-for="item in selectedPackage.items"
                        :key="item.id"
                        class="item-tag"
                        size="small"
                      >
                        {{ item.name }}
                      </el-tag>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <!-- 其他信息 -->
        <el-col :span="24">
          <el-card class="form-section">
            <template #header>
              <span>其他信息</span>
            </template>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="预约状态" prop="status">
                  <el-select
                    v-model="form.status"
                    placeholder="请选择状态"
                    style="width: 100%"
                  >
                    <el-option label="待确认" value="pending" />
                    <el-option label="已确认" value="confirmed" />
                    <el-option label="进行中" value="in_progress" />
                    <el-option label="已完成" value="completed" />
                    <el-option label="已取消" value="cancelled" />
                  </el-select>
                </el-form-item>
              </el-col>
              
              <el-col :span="12">
                <el-form-item label="紧急程度">
                  <el-radio-group v-model="form.priority">
                    <el-radio label="normal">普通</el-radio>
                    <el-radio label="urgent">紧急</el-radio>
                    <el-radio label="emergency">急诊</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              
              <el-col :span="24">
                <el-form-item label="特殊要求">
                  <el-input
                    v-model="form.specialRequirements"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入特殊要求或注意事项"
                    maxlength="500"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
              
              <el-col :span="24">
                <el-form-item label="备注信息">
                  <el-input
                    v-model="form.remark"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入备注信息"
                    maxlength="500"
                    show-word-limit
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ mode === 'create' ? '创建预约' : '保存修改' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  appointment: {
    type: Object,
    default: null
  },
  mode: {
    type: String,
    default: 'create' // create | edit
  }
})

// Emits
const emit = defineEmits(['update:visible', 'success'])

// 响应式数据
const formRef = ref()
const submitLoading = ref(false)
const patientLoading = ref(false)
const selectedPatient = ref(null)
const selectedPackage = ref(null)

// 表单数据
const form = reactive({
  patientId: '',
  packageId: '',
  appointmentDate: '',
  appointmentTime: '',
  doctor: '',
  status: 'pending',
  priority: 'normal',
  specialRequirements: '',
  remark: ''
})

// 表单验证规则
const rules = {
  patientId: [
    { required: true, message: '请选择患者', trigger: 'change' }
  ],
  packageId: [
    { required: true, message: '请选择体检套餐', trigger: 'change' }
  ],
  appointmentDate: [
    { required: true, message: '请选择预约日期', trigger: 'change' }
  ],
  appointmentTime: [
    { required: true, message: '请选择预约时间', trigger: 'change' }
  ]
}

// 模拟数据
const patients = ref([
  {
    id: 1,
    name: '张三',
    phone: '13800138001',
    gender: 'male',
    age: 35,
    idCard: '110101198901010001',
    bloodType: 'A',
    allergies: '青霉素过敏'
  },
  {
    id: 2,
    name: '李四',
    phone: '13800138002',
    gender: 'female',
    age: 28,
    idCard: '110101199501010002',
    bloodType: 'B',
    allergies: ''
  },
  {
    id: 3,
    name: '王五',
    phone: '13800138003',
    gender: 'male',
    age: 42,
    idCard: '110101198201010003',
    bloodType: 'O',
    allergies: '海鲜过敏'
  }
])

const packages = ref([
  {
    id: 1,
    name: '基础体检套餐',
    price: 299,
    description: '适合年轻人的基础体检项目，包含常规检查和基本化验',
    items: [
      { id: 1, name: '血常规' },
      { id: 2, name: '尿常规' },
      { id: 3, name: '心电图' },
      { id: 4, name: '胸部X光' },
      { id: 5, name: '肝功能' }
    ]
  },
  {
    id: 2,
    name: '全面体检套餐',
    price: 599,
    description: '全面的健康检查，适合中年人群，包含多项专业检查',
    items: [
      { id: 1, name: '血常规' },
      { id: 2, name: '尿常规' },
      { id: 3, name: '心电图' },
      { id: 4, name: '胸部X光' },
      { id: 5, name: '肝功能' },
      { id: 6, name: '肾功能' },
      { id: 7, name: 'B超检查' },
      { id: 8, name: '血脂检查' }
    ]
  },
  {
    id: 3,
    name: '高端体检套餐',
    price: 1299,
    description: '高端全面体检，包含最新设备检查和专家会诊',
    items: [
      { id: 1, name: '血常规' },
      { id: 2, name: '尿常规' },
      { id: 3, name: '心电图' },
      { id: 4, name: '胸部CT' },
      { id: 5, name: '肝功能' },
      { id: 6, name: '肾功能' },
      { id: 7, name: '彩超检查' },
      { id: 8, name: '血脂检查' },
      { id: 9, name: 'MRI检查' },
      { id: 10, name: '专家会诊' }
    ]
  }
])

const doctors = ref([
  { id: 1, name: '张医生', title: '主任医师' },
  { id: 2, name: '李医生', title: '副主任医师' },
  { id: 3, name: '王医生', title: '主治医师' },
  { id: 4, name: '陈医生', title: '住院医师' }
])

const availableTimes = ref([
  { value: '08:00', label: '08:00', disabled: false },
  { value: '08:30', label: '08:30', disabled: false },
  { value: '09:00', label: '09:00', disabled: false },
  { value: '09:30', label: '09:30', disabled: true },
  { value: '10:00', label: '10:00', disabled: false },
  { value: '10:30', label: '10:30', disabled: false },
  { value: '11:00', label: '11:00', disabled: false },
  { value: '11:30', label: '11:30', disabled: false },
  { value: '14:00', label: '14:00', disabled: false },
  { value: '14:30', label: '14:30', disabled: false },
  { value: '15:00', label: '15:00', disabled: false },
  { value: '15:30', label: '15:30', disabled: true },
  { value: '16:00', label: '16:00', disabled: false },
  { value: '16:30', label: '16:30', disabled: false }
])

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 监听器
watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      nextTick(() => {
        initForm()
      })
    }
  }
)

watch(
  () => props.appointment,
  (appointment) => {
    if (appointment && props.visible) {
      initForm()
    }
  }
)

// 方法
const initForm = () => {
  if (props.mode === 'edit' && props.appointment) {
    // 编辑模式，填充表单数据
    Object.assign(form, {
      patientId: props.appointment.patientId,
      packageId: props.appointment.packageId,
      appointmentDate: props.appointment.appointmentDate,
      appointmentTime: props.appointment.appointmentTime,
      doctor: props.appointment.doctor,
      status: props.appointment.status,
      priority: props.appointment.priority || 'normal',
      specialRequirements: props.appointment.specialRequirements || '',
      remark: props.appointment.remark || ''
    })
    
    // 设置选中的患者和套餐
    handlePatientChange(form.patientId)
    handlePackageChange(form.packageId)
  } else {
    // 创建模式，重置表单
    resetForm()
  }
}

const resetForm = () => {
  Object.assign(form, {
    patientId: '',
    packageId: '',
    appointmentDate: '',
    appointmentTime: '',
    doctor: '',
    status: 'pending',
    priority: 'normal',
    specialRequirements: '',
    remark: ''
  })
  selectedPatient.value = null
  selectedPackage.value = null
  formRef.value?.clearValidate()
}

const searchPatients = (query) => {
  if (query) {
    patientLoading.value = true
    // 模拟搜索API
    setTimeout(() => {
      // 这里可以根据query过滤患者列表
      patientLoading.value = false
    }, 300)
  }
}

const handlePatientChange = (patientId) => {
  const patient = patients.value.find(p => p.id === patientId)
  selectedPatient.value = patient
}

const handlePackageChange = (packageId) => {
  const pkg = packages.value.find(p => p.id === packageId)
  selectedPackage.value = pkg
}

const handleDateChange = (date) => {
  // 当日期改变时，重置时间选择
  form.appointmentTime = ''
  // 这里可以根据日期获取可用时间段
  updateAvailableTimes(date)
}

const updateAvailableTimes = (date) => {
  // 模拟根据日期更新可用时间
  // 实际应用中应该调用API获取该日期的可用时间段
  console.log('更新可用时间段:', date)
}

const disabledDate = (time) => {
  // 禁用过去的日期
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

const handleCreatePatient = () => {
  ElMessage.info('新建患者功能待实现')
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    submitLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const message = props.mode === 'create' ? '预约创建成功' : '预约修改成功'
    ElMessage.success(message)
    
    emit('success')
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const handleReset = () => {
  resetForm()
}

const handleClose = () => {
  dialogVisible.value = false
}
</script>

<style scoped>
.appointment-form {
  max-height: 70vh;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 20px;
}

.form-section:last-child {
  margin-bottom: 0;
}

.patient-option {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.patient-name {
  font-weight: 500;
  color: #2c3e50;
}

.patient-info {
  font-size: 12px;
  color: #909399;
}

.selected-patient {
  margin-top: 16px;
}

.patient-details {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  line-height: 1.5;
}

.detail-item.full-width {
  flex-direction: column;
  align-items: flex-start;
  margin-top: 12px;
}

.detail-item label {
  font-weight: 500;
  color: #606266;
  min-width: 60px;
  margin-right: 8px;
}

.detail-item span {
  color: #2c3e50;
}

.allergy-info {
  background: #fff2e8;
  color: #e6a23c;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  margin-top: 4px;
}

.package-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.package-name {
  font-weight: 500;
  color: #2c3e50;
}

.package-price {
  color: #67c23a;
  font-weight: 600;
}

.selected-package {
  margin-top: 16px;
}

.package-details {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
}

.package-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.package-header h4 {
  margin: 0;
  color: #2c3e50;
}

.package-description {
  color: #606266;
  margin: 0 0 16px 0;
  line-height: 1.6;
}

.package-items h5 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 14px;
}

.items-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.item-tag {
  margin: 0;
}

.doctor-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.doctor-name {
  font-weight: 500;
  color: #2c3e50;
}

.doctor-title {
  color: #909399;
  font-size: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-card__header) {
  padding: 12px 20px;
  background: #fafafa;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-divider__text) {
  background: #f8f9fa;
  color: #606266;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 95% !important;
    margin: 5vh auto;
  }
  
  .patient-option,
  .package-option,
  .doctor-option {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .package-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .items-grid {
    gap: 4px;
  }
  
  .dialog-footer {
    flex-direction: column;
  }
  
  .dialog-footer .el-button {
    width: 100%;
  }
}

@media (max-width: 480px) {
  :deep(.el-dialog) {
    width: 100% !important;
    margin: 0;
    height: 100vh;
    border-radius: 0;
  }
  
  :deep(.el-dialog__header) {
    padding: 15px 20px;
  }
  
  :deep(.el-dialog__body) {
    padding: 10px 20px;
    height: calc(100vh - 120px);
    overflow-y: auto;
  }
  
  :deep(.el-dialog__footer) {
    padding: 15px 20px;
  }
  
  .detail-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .detail-item label {
    min-width: auto;
    margin-right: 0;
    margin-bottom: 4px;
  }
}
</style>